package com.example.gcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.accounts.AccountManager;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import com.example.gcode.*;
import com.gcloud.googledrive.ListGoogleFile;
//import com.gcloud.runtime.GCloudSingleton;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;

public class Archivos_back extends ListActivity {

	private ProgressDialog pDialog;

	private static final String TAG_NOMBRE = "messages";
	private static final String TAG_SERVICE = "Google Drive";
	Drive service;
	GoogleAccountCredential credential;
	private static final int REQUEST_ACCOUNT = 1;
	private static final int REQUEST_CONFIRMATION = 2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.archivos_list);

		credential = GoogleAccountCredential.usingOAuth2(
				getApplicationContext(), DriveScopes.DRIVE);
		startActivityForResult(credential.newChooseAccountIntent(),
				REQUEST_ACCOUNT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ACCOUNT:
			if (resultCode == RESULT_OK && data != null
					&& data.getExtras() != null) {
				String accountName = data
						.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				credential.setSelectedAccountName(accountName);
				service = getDriveServices(credential);
				// new CargarArchivos().execute();
				Log.i("GCLOUD", "Ya entre a doInBackground :)");
				ListGoogleFile listGoogle = new ListGoogleFile(service,
						getApplicationContext());
				Log.i("OnActivitty", "before to execute");
				try {
					listGoogle.execute();
				} catch (Exception e) {
					Log.i("Exception catch", e.toString());
//					startActivityForResult(credential.newChooseAccountIntent(),
//							REQUEST_CONFIRMATION);
				}
				Log.i("OnActivitty", "after execute");

			}
			break;
//		case REQUEST_CONFIRMATION:
//			startActivityForResult(credential.newChooseAccountIntent(),
//					REQUEST_ACCOUNT);
//			break;
		}
	}

	private Drive getDriveServices(GoogleAccountCredential credential) {
		return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
				new GsonFactory(), credential).build();
	}

	class CargarArchivos extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Archivos_back.this);
			pDialog.setMessage("cargando archivos ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... voids) {

			Log.i("GCLOUD", "Ya entre a doInBackground :)");

			new ListGoogleFile(service, getApplicationContext()).execute();

			return "true";
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// if(){
			// startActivityForResult(credential.newChooseAccountIntent(),
			// REQUEST_ACCOUNT);
			// }
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					GCloudSingleton gSingleton = GCloudSingleton.getInstance();
					Log.i("Archivos:"," "+gSingleton.getFilesFromAllService().size());
					ListAdapter adapter = new SimpleAdapter(Archivos_back.this,
							gSingleton.getFilesFromAllService(),
							R.layout.archivos_list_item, new String[] {
									TAG_NOMBRE, TAG_SERVICE }, new int[] {
									R.id.list_nombre, R.id.list_service });
					// updating listview
					setListAdapter(adapter);
				}
			});

		}

	}
}